<?php

namespace App\Http\Controllers;

use App\Models\User\User as UserModel;
use App\Models\Region as RegionModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    // 用户中心
    public function index(Request $request)
    {
        $LoginUser = $request->cookie('LoginUser') ? json_decode($request->cookie('LoginUser'),true) : [];

        $data = compact([
            'LoginUser'
        ]);

        return view('home.user.index',$data);
    }

    // 基本资料
    public function profile(Request $request)
    {
        $LoginUser = $request->cookie('LoginUser') ? json_decode($request->cookie('LoginUser'),true) : [];

        // 查询省份
        $province = RegionModel::where(['grade' => 1])->select('code','name')->get();

        // 查询市
        if($LoginUser['province'])
        {
            $city = RegionModel::where(['parentid' => $LoginUser['province']])->select('code','name')->get();
        }else{
            $city = [];
        }

        // 查询区
        if($LoginUser['city'])
        {
            $district = RegionModel::where(['parentid' => $LoginUser['city']])->select('code','name')->get();
        }else{
            $district = [];
        }

        $data = compact([
            'LoginUser',
            'province',
            'city',
            'district'
        ]);

        return view('home.user.profile',$data);
    }

    // 处理修改资料逻辑
    public function profileform(Request $request)
    {
        $LoginUser = $request->cookie('LoginUser') ? json_decode($request->cookie('LoginUser'),true) : [];

        $userid = !empty($LoginUser['id']) ? $LoginUser['id'] : 0;

        $User = UserModel::find($userid);

        if(!$User)
        {
            // 清除cookie
            Cookie::queue(Cookie::forget('LoginUser'));

            return redirect()->route('error',['msg' => '非法登录，请重新登录','url' => url('home/user/login')]);
        }

        // 接收全部参数
        $params = $request->all();

        // 封装更新数组
        $data = [
            'nickname' => $params['nickname'],
            'sex' => $params['sex'],
            'phone' => $params['phone'],
            'province' => $params['province'],
            'city' => $params['city'],
            'district' => $params['district']
        ];

        // 修改密码
        if(!empty($params['password']))
        {
            // 生成一个新的密码盐
            $salt = build_ranstr();

            // 加密
            $password = md5($params['password'].$salt);

            // 追加数组
            $data['password'] = $password;

            $data['salt'] = $salt;
        }

        // 修改头像
        if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
        {
            // file => 接收上传文件 store => 保存文件 第一个参数 指定路径 第二个参数 指定磁盘
            $file = $request->file('avatar')->store('images','uploads');

            $data['avatar'] = $file;
        }

        $result = UserModel::where(['id' => $userid])->update($data);

        if($result === FALSE)
        {
            if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
            {
                Storage::disk('uploads')->delete($file);
            }

            return redirect()->route('error',['msg' => '修改失败']);
        }else{
            if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
            {
                Storage::disk('uploads')->delete($User->avatar);
            }

            $user = UserModel::find($userid);

            // 封装cookie数据
            $data = [
                'id' => $user['id'],
                'nickname' => $user['nickname'],
                'email' => $user['email'],
                'phone' => $user['phone'],
                'avatar' => $user['avatar'],
                'sex' => $user['sex'],
                'province' => $user['province'],
                'city' => $user['city'],
                'district' => $user['district'],
                'createtime' => $user['createtime'],
            ];

            // 数组转成json数据
            $UserJson = json_encode($data);

            // 设置cookie
            Cookie::queue('LoginUser',$UserJson);

            return redirect()->route('success',['msg' => '修改成功','url' => url('home/user/index')]);

        }
    }

    // 查询地区
    public function area()
    {
        $code = request('code');

        $region = RegionModel::where(['parentid' => $code])->select('code','name')->get();

        if(!$region)
        {
            return json_encode(['code' => 0,'url' => '所选地区不存在，请重新选择']);
        }

        return json_encode(['code' => 1,'url' => '查询成功','data' => $region]);

    }

    // 登录
    public function login(Request $request)
    {
        $LoginUser = $request->cookie('LoginUser') ? json_decode($request->cookie('LoginUser'),true) : [];

        if(!empty($LoginUser))
        {
             // 获取用户id
            $userid = !empty($LoginUser['id']) ? $LoginUser['id'] : 0;
            
            // 查询用户表里是否存在该用户
            $User = UserModel::find($userid);

            if(!$User)
            {
                Cookie::queue(Cookie::forget('LoginUser'));
                return redirect()->route('error',['msg' => '非法登录','url' => url('home/user/login')]);
            }

            return redirect()->route('success',['msg' => '您已经登录了，无须重复登录','url' => url('home/user/index')]);
        }

        return view('home.user.login');
    }

    // 处理登录逻辑
    public function loginform(Request $request)
    {
        $params = $request->all();

        $User = UserModel::where(['email' => $params['email']])->first();

        if(!$User)
        {
            return redirect()->route('error',['msg' => '该邮箱未注册，请更换邮箱登录']);
        }

        $password = md5($params['password'].$User->salt);

        if($password != $User['password'])
        {
            return redirect()->route('error',['msg' => '密码错误，请重新输入']);
        }

        // 封装cookie数据
        $data = [
            'id' => $User['id'],
            'nickname' => $User['nickname'],
            'email' => $User['email'],
            'phone' => $User['phone'],
            'avatar' => $User['avatar'],
            'sex' => $User['sex'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
        ];

        // 数组转成json数据
        $UserJson = json_encode($data);

        // 设置cookie
        Cookie::queue('LoginUser',$UserJson);

        return redirect()->route('success',['msg' => '登录成功','url' => url('home/user/index')]);
    }

    // 注册
    public function register(Request $request)
    {
        $LoginUser = $request->cookie('LoginUser') ? json_decode($request->cookie('LoginUser'),true) : [];

        if(!empty($LoginUser))
        {
             // 获取用户id
            $userid = !empty($LoginUser['id']) ? $LoginUser['id'] : 0;
            
            // 查询用户表里是否存在该用户
            $User = UserModel::find($userid);

            if(!$User)
            {
                Cookie::queue(Cookie::forget('LoginUser'));
                return redirect()->route('error',['msg' => '非法登录','url' => url('home/user/login')]);
            }

            return redirect()->route('success',['msg' => '您已经登录了，无须重复登录','url' => url('home/user/index')]);
        }

        return view('home.user.register');
    }

    // 处理注册逻辑
    public function registerform(Request $request)
    {
        $params = $request->all();

        $params['salt'] = build_ranstr();

        // 表单验证规则
        $rules = [
            'email' => 'required|unique:user|email',
            'password' => 'required',
            'salt' => 'required'
        ];

        // 错误信息
        $message = [
            'email.required' => '邮箱必填',
            'email.unique' => '该邮箱已注册，请重新输入',
            'email.email' => '邮箱格式不对',
            'password.required' => '密码必填',
            'salt.required' => '密码盐未知'
        ];

        $validator = Validator::make($params,$rules,$message);

        if($validator->fails())
        {
            return redirect('home/user/register')->withErrors($validator)->withInput();
        }

        $data = [
            'email' => $params['email'],
            'password' => md5($params['password'].$params['salt']),
            'salt' => $params['salt']
        ];

        $result = UserModel::create($data);

        if($result === FALSE)
        {
            return redirect()->route('error',['msg' => '注册失败']);
        }else{
            return redirect()->route('success',['msg' => '注册成功','url' => url('home/user/login')]);
        }
    }

    // 退出
    public function logout()
    {
        Cookie::queue(Cookie::forget('LoginUser'));

        return json_encode(['code' => 1,'msg' => '退出成功']);
    }
}
